using B.S.XZYData.Api.Read.Application.Command.SalesOrder;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using SqlSugar;
using SalesOrderEntity = B.S.XZYData.Domain.XZY.SalesOrder;

namespace B.S.XZYData.Api.Read.Application.Handler.SalesOrder
{
    /// <summary>
    /// 查询销售订单处理器
    /// </summary>
    public class QuerySalesOrderHandler : IRequestHandler<QuerySalesOrderCommand, ApiResult<ApiPageing<SalesOrderDTO>>>
    {
        private readonly IBaseRepository<SalesOrderEntity> _salesOrderRepo;

        public QuerySalesOrderHandler(IBaseRepository<SalesOrderEntity> salesOrderRepo)
        {
            _salesOrderRepo = salesOrderRepo;
        }

        public async Task<ApiResult<ApiPageing<SalesOrderDTO>>> Handle(QuerySalesOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _salesOrderRepo.GetAll()
                    .Where(x => !x.IsDeleted);

                // 单据编号筛选
                if (!string.IsNullOrEmpty(request.OrderNo))
                {
                    query = query.Where(x => x.OrderNo.Contains(request.OrderNo));
                }

                // 备注筛选
                if (!string.IsNullOrEmpty(request.Remark))
                {
                    query = query.Where(x => x.Remark != null && x.Remark.Contains(request.Remark));
                }

                // 按创建时间倒序
                query = query.OrderByDescending(x => x.CreateTime);

                // 分页查询
                var total = await query.CountAsync();
                var list = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO
                var dtoList = list.Select(x => new SalesOrderDTO
                {
                    Id = x.Id,
                    OrderNo = x.OrderNo,
                    Remark = x.Remark,
                    CreateTime = x.CreateTime,
                    CreatorName = "超级管理员", // 这里应该根据CreatorId查询用户表获取用户名
                    ModifierName = x.ModifierId.HasValue ? "超级管理员" : null, // 这里应该根据ModifierId查询用户表获取用户名
                    ModifyTime = x.ModifyTime
                }).ToList();

                var result = new ApiPageing<SalesOrderDTO>
                {
                    TotaCount = total,
                    PageData = dtoList
                };

                return ApiResult<ApiPageing<SalesOrderDTO>>.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResult<ApiPageing<SalesOrderDTO>>.Error($"查询销售订单失败：{ex.Message}");
            }
        }
    }
}
